import axios from "axios"
import router from "@/router/index";
axios.defaults.withCredentials = false   //阻止ajax附带cookie
const errorHandle = (status,info) => {
    switch(status){
      case 400:
        console.log("语义有误");
        break;
      case 401:
        console.log("服务器认证失败");
        break;
      case 403:
        console.log("服务器拒绝访问");
        break;
      case 404:
        console.log("地址错误");
        break;
      case 500:
        console.log("服务器遇到意外");
        break;
      case 502:
        console.log("服务器无响应");
        break;
      default:
        console.log(info);
        break;
     }
  }
const instance = axios.create({
    timeout:5000
})


const getAccessToken = () => localStorage.getItem('token') || sessionStorage.getItem('token');
const getRefreshToken = () => localStorage.getItem('refresh') || sessionStorage.getItem('refresh');
instance.interceptors.request.use(
    config => {
      const token = getAccessToken();
      if (token) config.headers.Authorization = `Bearer ${token}`;
      return config;
    },
    error=>{
        return Promise.reject(error)
    }
)


instance.interceptors.response.use(
  response => response,
  async error => {
    const { config, response } = error;
    
    // 1. 处理 401 错误
    if (response?.status === 401) {
      const refreshToken = getRefreshToken();
      
      // 2. 如果有 Refresh Token，尝试刷新
      if (refreshToken) {
        try {
          // 调用刷新 Token 的 API
          const { data } = await axios.post('http://localhost:8000/user/refresh/', { refresh: refreshToken });
          // console.log(data)
          // 3. 存储新 Token
          localStorage.setItem('token', data.access);
          localStorage.setItem('refresh', data.refresh);
          
          // 4. 重试原始请求
          config.headers.Authorization = `Bearer ${data.access}`;
          return instance(config);
        } catch (refreshError) {
          // 刷新失败，跳转登录
          console.log('刷新失败')
          logout();
        }
      } else {
        logout();
      }
    }
    
    return Promise.reject(error);
  }
);

const logout = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('refresh');
  localStorage.removeItem('user_id');
  sessionStorage.removeItem('token');
  sessionStorage.removeItem('refresh');
  sessionStorage.removeItem('user_id');
  router.push('/login');
};

export default instance